package com.work.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.work.work.dto.TeamMemberDTO;
import com.work.work.entity.Role;
import com.work.work.entity.Team;
import com.work.work.entity.User;
import com.work.work.mapper.RoleMapper;
import com.work.work.mapper.TeamMapper;
import com.work.work.mapper.UserMapper;
import com.work.work.service.TeamService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    @Transactional
    public boolean createTeam(Team team) {
        if (team.getTeamname() == null || team.getTeamname().trim().isEmpty()) {
            return false;
        }
        return save(team);
    }

    @Override
    @Transactional
    public boolean updateTeam(Team team) {
        if (team.getId() == null || team.getTeamname() == null || team.getTeamname().trim().isEmpty()) {
            return false;
        }
        return updateById(team);
    }

    @Override
    public Page<Team> getTeamList(Integer current, Integer size) {
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Team::getId);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public List<Team> getAllTeams() {
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Team::getId);
        return list(queryWrapper);
    }


    @Override
    public List<TeamMemberDTO> getTeamMembers(Integer teamId) {
        // 查询指定团队的所有用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getTeamId, teamId);

        List<User> users = userMapper.selectList(queryWrapper);

        // 获取团队信息
        Team team = getById(teamId);

        // 转换为DTO对象
        return users.stream().map(user -> {
            TeamMemberDTO dto = new TeamMemberDTO();
            BeanUtils.copyProperties(user, dto);

            // 设置团队信息
            if (team != null) {
                dto.setTeamname(team.getTeamname());
            }

            // 获取并设置角色信息
            Role role = roleMapper.selectById(user.getRoleId());
            if (role != null) {
                dto.setRolename(role.getRolename());
            }

            return dto;
        }).collect(Collectors.toList());
    }
}